package cn.iot.sys.service.impl;

import cn.iot.common.dto.ResultMsg;
import cn.iot.sys.dao.SysFaceRecordDao;
import cn.iot.sys.entity.SysFaceRecord;
import cn.iot.sys.entity.SysRule;
import cn.iot.sys.service.SysFaceRecordService;
import cn.iot.util.TimeSectionData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netsdk.demo.module.LoginModule;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysFaceRecordServiceImpl extends ServiceImpl<SysFaceRecordDao, SysFaceRecord> implements SysFaceRecordService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public int addFaceRecord(SysFaceRecord sysFaceRecord) {
        logger.info("SysFaceRecordServiceImpl addFaceRecord sysFaceRecord{}",sysFaceRecord);
        sysFaceRecord.setRecognitionTime(new Date());
        sysFaceRecord.setCreateDate(new Date());
        int count = this.baseMapper.insert(sysFaceRecord);
        return count;
    }

    @Override
    public ResultMsg getFaceRecordList(Map<String, Object> map) {
        logger.info("SysFaceRecordServiceImpl getFaceRecordList map{}",map);
        int pageNum = Integer.parseInt((String)map.get("pageNum"));
        int pageSize = Integer.parseInt((String)map.get("pageSize"));
        QueryWrapper<SysFaceRecord> queryWrapper = new QueryWrapper<>();
        //降序
        queryWrapper.orderByDesc("createDate");
        IPage<SysFaceRecord> page = new Page<>(pageNum,pageSize);
        IPage<SysFaceRecord> page1 = this.baseMapper.selectPage(page, queryWrapper);
        int count = this.baseMapper.selectCount(queryWrapper);
        int pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        List<SysFaceRecord> sysFaceRecordList = page1.getRecords();
        map.put("sysFaceRecordList",sysFaceRecordList);
        map.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",map);
        return msg;
    }

    /**
     * 规则添加
     * @param sysRule
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public boolean setAccessTimeSchedule(SysRule sysRule) throws UnsupportedEncodingException {
        LoginModule.logout();
        LoginModule.init(null, null);

        // TODO 1 登录设备
        boolean isLogin = LoginModule.login("192.168.1.198", 37777, "admin", "Admin123456");
        if (!isLogin) {
            return false;
        }
        // TODO 2 获取当前的时间配置
        NetSDKLib.CFG_ACCESS_TIMESCHEDULE_INFO time = new NetSDKLib.CFG_ACCESS_TIMESCHEDULE_INFO(); // 时间配置对象
        boolean result = ToolKits.GetDevConfig(LoginModule.m_hLoginHandle, -1, NetSDKLib.CFG_CMD_ACCESSTIMESCHEDULE, time);

        time.szName = "1112".getBytes("GBK");
        // TODO 配置失败，退出设备
        if (!result) {
            LoginModule.logout();
            return false;
        }
        // TODO 获取一周的时间配置
        List<String> weeklyTimeSections = Arrays.asList(sysRule.getWeek1(), sysRule.getWeek2(), sysRule.getWeek3(),sysRule.getWeek4(), sysRule.getWeek5(), sysRule.getWeek6(), sysRule.getWeek7());

        ObjectMapper objectMapper = new ObjectMapper(); // 用于解析 JSON 数据
        // TODO 设置时间配置
        for (int i = 0; i < weeklyTimeSections.size(); i++) {
            try {
                String json = weeklyTimeSections.get(i);
                List<TimeSectionData> timeSectionDataList = objectMapper.readValue(json, new com.fasterxml.jackson.core.type.TypeReference<List<TimeSectionData>>() {});
                for (int j = 0; j < timeSectionDataList.size() && j < time.stuTimeWeekDay[i].stuTimeSection.length; j++) {
                    TimeSectionData data = timeSectionDataList.get(j);
                    List<String> section = data.getEndTime();
                    String[] startTime = section.get(0).split(":");
                    String[] endTime = section.get(1).split(":");
                    time.stuTimeWeekDay[i].stuTimeSection[j].dwRecordMask = 1;
                    time.stuTimeWeekDay[i].stuTimeSection[j].setStartTime(Integer.parseInt(startTime[0]), Integer.parseInt(startTime[1]), Integer.parseInt(startTime[2]));
                    time.stuTimeWeekDay[i].stuTimeSection[j].setEndTime(Integer.parseInt(endTime[0]), Integer.parseInt(endTime[1]), Integer.parseInt(endTime[2]));
                }
            } catch (Exception e) {
                e.printStackTrace();
                LoginModule.logout();
                return false;
            }
        }
        result = ToolKits.SetDevConfig(LoginModule.m_hLoginHandle, Integer.parseInt(sysRule.getDeviceCode()), NetSDKLib.CFG_CMD_ACCESSTIMESCHEDULE, time);

        // 登出设备
        LoginModule.logout();
        return result;
    }

}
